package m.member.manage.service;

import m.common.model.util.ModelCheckUtil;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.Service;
import m.member.manage.model.LevelUpSet;
import m.member.manage.model.MemberInfo;
import m.system.cache.CacheUtil;
import m.system.exception.MException;
import m.system.util.GenerateID;
import m.system.util.ObjectUtil;

import java.util.ArrayList;
import java.util.List;

public class LevelUpSetService extends Service {
    public String save(LevelUpSet model) throws Exception {
        ModelCheckUtil.checkNotNull(model,"beforeLevel.oid","afterLevel.oid","useMoney","orderNum");
        ModelCheckUtil.checkUniqueCombine(model,new String[]{"beforeLevel.oid"},"当前会员升级配置已经存在，请直接修改！");
        LevelUpSet up=new LevelUpSet();
        up.setOid(model.getOid());
        up.setBeforeLevel(model.getAfterLevel());
        up.setAfterLevel(model.getBeforeLevel());
        ModelCheckUtil.checkUniqueCombine(up,new String[]{"beforeLevel.oid","afterLevel.oid"},"无法设置这样的升级配置！");
        if(model.getBeforeLevel().getOid().equals(model.getAfterLevel().getOid())){
            throw new MException(this.getClass(),"升级后的会员不能与当前会员相同！");
        }
        String msg;
        if (ObjectUtil.isEmptyOid(model)) {
            model.setOid(GenerateID.generatePrimaryKey());
            ModelUpdateUtil.insertModel(model);
            msg="保存成功";
        }else{
            ModelUpdateUtil.updateModel(model);
            msg="修改成功";
        }
        CacheUtil.clear(LevelUpSet.class);
        return msg;
    }
    public void autoUpSet(String memberOid) throws MException {
        MemberInfo member= CacheUtil.get(MemberInfo.class,memberOid);
        LevelUpSet up=CacheUtil.get(LevelUpSet.class,member.getLevel().getOid());
        if(null!=up){
            //同时满足使用金额和订单金额到达目标时升级
            if(member.getUseMoney()>=up.getUseMoney()&&member.getOrderNum()>=up.getOrderNum()){
                member.setLevel(up.getAfterLevel());
                ModelUpdateUtil.updateModel(member,"level.oid");
                CacheUtil.clear(MemberInfo.class,memberOid);
            }
        }
    }
}
